package com.lm.javafx.example;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class WebViewJavaScriptDemo extends Application {

    @Override
    public void start(Stage primaryStage) {
        WebView webView = new WebView();
        WebEngine webEngine = webView.getEngine();
        webEngine.loadContent("<html><body><h2>Java 与 JavaScript 交互</h2></body></html>");

        // 处理 JavaScript alert 弹窗
        webEngine.setOnAlert(event -> {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("JavaScript Alert");
            alert.setHeaderText(null);
            alert.setContentText(event.getData());
            alert.showAndWait();
        });

        // 创建按钮，点击后触发 Java 调用 JavaScript
        Button button = new Button("调用 JavaScript");
        button.setOnAction(event -> webEngine.executeScript("alert('Java 调用 JavaScript!');"));


        VBox root = new VBox(webView, button);
        Scene scene = new Scene(root, 800, 600);

        primaryStage.setTitle("JavaFX WebView JavaScript 交互");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}